package com.auerdi.ui.detail.cutprice.detail;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.auerdi.GlideApp;
import com.auerdi.R;
import com.auerdi.dialog.CateGoryCutDialog;
import com.auerdi.ui.detail.ADProductDetailFragment;
import com.auerdi.ui.detail.cutprice.detail.child.ADCutDetailACompoDetail;
import com.auerdi.ui.detail.cutprice.detail.child.ADCutDetailBCompoFriend;
import com.auerdi.ui.detail.cutprice.detail.child.ADCutDetailCCompoBestCut;
import com.auerdi.ui.detail.cutprice.event.POPtomyCut;
import com.auerdi.ui.fragment.c_officer.OtherPagerFragment;
import com.auerdi.ui.view.TriangleRectangleLabelView;
import com.auerdi.ui.view.scrollviewwithstickheader.ScrollViewWithStickHeader;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.egghttp.EggLog.L;
import com.example.egghttp.RetrofitClient;
import com.example.egghttp.retrofit.AdService;
import com.example.egghttp.retrofit.beans.BOb;
import com.example.egghttp.retrofit.beans.banner.BargainDatailResp;
import com.example.egghttp.retrofit.beans.banner.GoodLoveList;
import com.example.egghttp.retrofit.beans.banner.Img;
import com.example.egghttp.retrofit.beans.banner.StartACtivityResponce;
import com.example.egghttp.retrofit.beans.goods.CutProduct;
import com.example.egghttp.retrofit.beans.goods.Product;
import com.example.egghttp.retrofit.interceptor.Token;
import com.example.egghttp.retrofit.params.BarHagRequest;
import com.example.egghttp.retrofit.params.BargainDatailRequest;
import com.squareup.picasso.Picasso;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import net.sourceforge.simcpux.Constants;
import net.sourceforge.simcpux.Util;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import es.dmoral.toasty.Toasty;
import me.yokeyword.eventbusactivityscope.EventBusActivityScope;
import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by YoKeyword on 16/2/14.
 */
public class ADCutProductDetailFragmentM extends SwipeBackFragment {


    private static CutProduct mProduct;
    @BindView(R.id.title_left)
    View titleLeft;
    Unbinder unbinder;
    @BindView(R.id.statusBar)
    View statusBar;
    @BindView(R.id.order_manager_tabs)
    TabLayout mOrderManagerTabs;
    @BindView(R.id.vp)
    ViewPager mVp;
    @BindView(R.id.ll_stick_list)
    LinearLayout mLLStickList;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.stick_scroll_view)
    ScrollViewWithStickHeader mStickScrollView;
    @BindView(R.id.backhome)
    LinearLayout backhome;
    @BindView(R.id.cusser)
    LinearLayout cusser;
    @BindView(R.id.buynow)
    View buynow;
    @BindView(R.id.groupbuy)
    LinearLayout groupbuy;
    @BindView(R.id.bottom)
    LinearLayout mViewBottom;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.title_txt)
    TextView titleTxt;
    @BindView(R.id.gpic)
    ImageView gpic;
    @BindView(R.id.gname)
    TextView gname;
    @BindView(R.id.apri)
    TextView apri;
    @BindView(R.id.bpri)
    TextView bpri;
    @BindView(R.id.num)
    TextView num;
    @BindView(R.id.des_txt)
    TextView desTxt;
    @BindView(R.id.trv_name)
    TriangleRectangleLabelView trvName;
    @BindView(R.id.www)
    TextView www;
    @BindView(R.id.hour_txt)
    TextView hourTxt;
    @BindView(R.id.minute_txt)
    TextView minuteTxt;
    @BindView(R.id.second_txt)
    TextView secondTxt;
    @BindView(R.id.floor)
    TextView floor;
    @BindView(R.id.tualist)
    RecyclerView tualist;
    @BindView(R.id.start_cut_btn)
    TextView startCutBtn;
    private List<Product> mEveryBodyLisy = new ArrayList<>();
    private static final int THUMB_SIZE = 150;
    private int mTargetScene = SendMessageToWX.Req.WXSceneSession;

    private IWXAPI api;
    private BargainDatailResp bargainDatailResp;
    private Subscription eew;

    public static ADCutProductDetailFragmentM newInstance(CutProduct product) {
        Bundle args = new Bundle();
        mProduct = product;
        ADCutProductDetailFragmentM fragment = new ADCutProductDetailFragmentM();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(getActivity(), Constants.APP_ID);

    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        reaquestDetailCut();


        RetrofitClient.getPDAClient().create(AdService.class).goodsEverybodys()//大家都在團
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<GoodLoveList>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BOb<GoodLoveList> goodLoveListBOb) {
                        List<Product> bodyLsiy = goodLoveListBOb.getBody().getProLists();
                        mEveryBodyLisy.clear();
                        mEveryBodyLisy.addAll(bodyLsiy);
                        tualist.getAdapter().notifyDataSetChanged();

                    }
                });

    }

    private void shareWechat(BargainDatailResp bargainDatailResp) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = "http://www.auerdi.com/index.php/User-kanjia-zid-" + bargainDatailResp.getGoods_id() + "-zsid-" + bargainDatailResp.getBargain_id() + "-fromuser-" + Token.getUID() + ".html";
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = bargainDatailResp.getGoods_name();
        msg.description = bargainDatailResp.getShare_title();


        final Bitmap[] bmp = new Bitmap[1];
        Glide.with(getActivity())
                .asBitmap()//强制Glide返回一个Bitmap对象
                .load(bargainDatailResp.getProduct_country_logo())
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap bitmap,
                                                Transition<? super Bitmap> transition) {
//                                                    imageView.setImageBitmap(bitmap);

                        bmp[0] = bitmap;
                        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp[0], THUMB_SIZE, THUMB_SIZE, true);
                        bmp[0].recycle();
                        msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.transaction = buildTransaction("webpage");
                        req.message = msg;
                        req.scene = mTargetScene;
                        api.sendReq(req);
                    }
                });
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        L.d("hcia", "onCreateView:");
        View view = inflater.inflate(R.layout.ad_fragment_product_detail_cut_v2, container, false);
        View tpview = attachToSwipeBack(view);
        unbinder = ButterKnife.bind(this, tpview);


        titleLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });


        mStickScrollView.setContentView(mLLStickList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        tualist.setLayoutManager(linearLayoutManager);
        tualist.setAdapter(new CommonAdapter<Product>(getActivity(), R.layout.item_home_love_v2, mEveryBodyLisy) {
            @Override
            protected void convert(ViewHolder viewHolder, final Product product, int position) {
                ImageView imgView = viewHolder.getView(R.id.img);
                ImageView gPic = viewHolder.getView(R.id.gpic);
                viewHolder.setText(R.id.title, product.getTitle());
                viewHolder.setText(R.id.gname, product.getBnProductGuojiaName());
                viewHolder.setText(R.id.stitle, product.getShareTitle());
                viewHolder.setText(R.id.apri, "¥" + product.getSuccessPrice());
                viewHolder.setText(R.id.bpri, "¥" + product.getMarkPrice());
                Picasso.get().load(product.getBnProductGuojia()).error(R.mipmap.logo).placeholder(R.mipmap.logo).fit().centerInside().into(gPic);

                GlideApp.with(viewHolder.getConvertView().getContext())
                        .load(product.getLunboImg())
                        .placeholder(R.mipmap.eptb)
                        .error(R.mipmap.pay_err)
                        .fitCenter()
                        .into(imgView);


                viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {


                        EventBusActivityScope.getDefault((Activity) viewHolder.getConvertView().getContext()).post(ADProductDetailFragment.newInstance(product));


                    }
                });

            }
        });

        buynow.setOnClickListener(v -> CateGoryCutDialog.newInstance(mProduct, "0").show(getFragmentManager(), ""));

        groupbuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareWechat(bargainDatailResp);


            }
        });
        cusser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                EventBus.getDefault().post(new POPtomyCut());

            }
        });
        mVp.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {

            @Override
            public int getCount() {
                return 3;
            }

            @Override
            public Fragment getItem(int position) {

                if (position == 0)
                    return ADCutDetailACompoDetail.newInstance();

                if (position == 1)
                    return ADCutDetailBCompoFriend.newInstance();

                if (position == 2)
                    return ADCutDetailCCompoBestCut.newInstance();


                return OtherPagerFragment.newInstance();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                if (position == 0) {
                    return "商品详情";
                }
                if (position == 1) {
                    return "好友贡献";
                }
                if (position == 2) {
                    return "砍神榜";
                }
                return "tab" + position;
            }
        });

        mVp.addOnPageChangeListener(
                new TabLayout.TabLayoutOnPageChangeListener(mOrderManagerTabs));
        mVp.setOffscreenPageLimit(3);
        mOrderManagerTabs.setupWithViewPager(mVp);


        return tpview;
    }

    private void reaquestDetailCut() {
        RetrofitClient.getPDAClient().create(AdService.class).bargainDetails(new BargainDatailRequest(mProduct.getBargain_id(), mProduct.getGoods_id(), "", "", ""))
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<BargainDatailResp>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        L.d("hcia", "e:" + e);

                    }

                    @Override
                    public void onNext(BOb<BargainDatailResp> bargainDatailRespBOb) {
//                        L.d("hcia", "bargainDatailRespBOb.getBody().getGoods_name():" + bargainDatailRespBOb.getBody().getGoods_name());
                        bargainDatailResp = bargainDatailRespBOb.getBody();

                        EventBus.getDefault().postSticky(bargainDatailResp);
                        EventBus.getDefault().postSticky(mProduct);


                        GlideApp.with(getActivity())
                                .load(bargainDatailRespBOb.getBody().getProduct_country_logo())
                                .placeholder(R.mipmap.eptb)
                                .error(R.mipmap.eptb)
                                .centerInside()
                                .into(gpic);


                        startCutBtn.setText(bargainDatailResp.getSelf_can_start().equals("1") ? "自砍一刀" : "直接买");
                        startCutBtn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {


                                if (bargainDatailResp.getSelf_can_start().equals("1")) {
                                    cutMe();
                                } else {
                                    CateGoryCutDialog.newInstance(mProduct, "0").show(getFragmentManager(), "");
                                }

                            }
                        });


                        titleTxt.setText(bargainDatailResp.getGoods_name());
                        desTxt.setText(bargainDatailResp.getShort_title());
                        apri.setText(bargainDatailResp.getFloor_price());
                        floor.setText(bargainDatailResp.getFloor_price());
                        num.setText("已有" + bargainDatailResp.getNumber_participants() + "参加");
                        bpri.setText("¥" + bargainDatailResp.getMarket_price());
                        bpri.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // 设置中划线并加清晰
                        gname.setText(bargainDatailResp.getProduct_country_name());
                        List<Img> coverList = bargainDatailResp.getCover_images_list();
                        banner.setImageLoader(new ImageLoader() {
                            @Override
                            public void displayImage(Context context, Object path, ImageView imageView) {
                                Img banner = (Img) path;
                                GlideApp.with(getActivity())
                                        .load(banner.getImg_url())
                                        .placeholder(R.mipmap.eptb)
                                        .error(R.mipmap.eptb)
                                        .centerInside()
                                        .into(imageView);


                            }
                        });

                        banner.setImages(coverList);
                        banner.start();

                        int count = Integer.parseInt(bargainDatailResp.getEnd_time());
//                        eew.unsubscribe();
//                        L.d("hcia", "eew.isUnsubscribed():" + eew.isUnsubscribed());

                        if (eew == null)
                            eew = Observable.interval(0, 1, TimeUnit.SECONDS)//设置0延迟，每隔一秒发送一条数据
                                    .take(count + 1) //设置循环11次
                                    .map(aLong -> count - aLong)
                                    .observeOn(AndroidSchedulers.mainThread())//操作UI主要在UI线程
                                    .subscribe(new Observer<Long>() {
                                        @Override
                                        public void onCompleted() {
                                        }

                                        @Override
                                        public void onError(Throwable e) {
                                            L.d("hcia", "e:" + e);
                                            e.printStackTrace();
                                        }

                                        @Override
                                        public void onNext(Long aLong) { //接受到e一条就是会操作一次UI

//                                        secondTxt.setText();
                                            long hh = aLong / 3600;
                                            long mm = (aLong - hh * 3600) / 60;
                                            long ss = aLong - hh * 3600 - mm * 60;
                                            secondTxt.setText("" + ss + "");
                                            minuteTxt.setText("" + mm + "");
                                            hourTxt.setText("" + hh + "");

//                                        btnCheck.setTextColor(Color.BLACK);

                                        }
                                    });


                    }
                });
    }

    private void cutMe() {
        RetrofitClient.getPDAClient().create(AdService.class).bargainHaggling(new BarHagRequest(mProduct.getBargain_id(), mProduct.getGoods_id()))
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<StartACtivityResponce>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        L.d("hcia", " e:" + e);

                    }

                    @Override
                    public void onNext(BOb<StartACtivityResponce> startACtivityResponceBOb) {
//                        L.d("hcia", ".getRaillery_text() getRaillery_text:" + startACtivityResponceBOb.getBody().getOrder_data().getRaillery_text());
//                        L.d("hcia", ".getRaillery_text() getStart_nickname:" + startACtivityResponceBOb.getBody().getOrder_data().getStart_nickname());

                        Toasty.success(getActivity(), startACtivityResponceBOb.getBody().getOrder_data().getRaillery_text()).show();
                        reaquestDetailCut();

//                        startCutBtn.setText("直接买");

                    }
                });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().removeStickyEvent(BargainDatailResp.class);
        EventBus.getDefault().removeStickyEvent(CutProduct.class);
        unbinder.unbind();
        eew.unsubscribe();

    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
}
